<?php
/*
 * Parsing and creating rss feeds
 * 
 * (c) Taras Kudla, 2010
 */

/* Converted to php rss channel format:
 * 	- title
 *  - link
 *  - description
 *  - image
 *  	- url
 *  	- title
 *  - item 1
 *  	- title
 *  	- description
 *  	- link
 *  	- fulltext
 *   	- author
 *   	- pubdate
 *   	- image
 *   	- media
 *   		- url
 *   		- title
 *			- type
 *	- item N 
 *		...
 */

class rss extends library { 

	public function parse($data){

		# parsing xml data, using simple_xml
		$xml = simplexml_load_string($data);
		$channel = $xml->channel;
		$rss["title"]=(string)$channel->title;
		$rss["link"]=(string)$channel->link;
		$rss["description"]=isset($channel->description)?(string)$channel->description:null;
		if( isset($channel->image)){
			$image = $channel->image;
			$rss["image"]["url"]=isset($image->url)?(string)$image->url:null;
			$rss["image"]["title"]=isset($image->title)?(string)$image->title:null;
		}
		$items = $channel->item;
		$rss["item"]=array();
		$i=0;
		foreach($items as $k=>$item){
			$rss["item"][$i]["title"]=isset($item->title)?(string)$item->title:null;
			$rss["item"][$i]["description"]=isset($item->description)?(string)$item->description:null;
			$rss["item"][$i]["fulltext"]=isset($item->fulltext)?(string)$item->fulltext:null;
			$rss["item"][$i]["pubdate"]=isset($item->pubDate)?(string)$item->pubDate:null;
			$rss["item"][$i]["author"]=isset($item->author)?(string)$item->author:null;
			$rss["item"][$i]["link"]=isset($item->link)?(string)$item->link:null;
			# image detection
			
			$i++;
		}
	return $rss;
	}
	
	public function validate($data){
		$this->api->setstate("exceptiononerror",true);
		try {
			$xml = simplexml_load_string($data);
			$channel = $xml->channel;
			if( !isset($channel->title))
				return false;			
		} catch(GepardException $e){
			$this->api->restorestate("exceptiononerror");
			return false;
		}
		$this->api->restorestate("exceptiononerror");
		return true;
	}
	
	public function load($url){
		$this->api->setstate("exceptiononerror",true);
		try {
			$data = @file_get_contents($url);
			$encoding = $this->api->get("charset");
			if( extension_loaded("mbstring")){
				$dataenc = mb_detect_encoding($data);
			if( strtolower($dataenc)!=strtolower($encoding))
				$data = mb_convert_encoding($data,$encoding,$dataenc); 
			}
			$xml = simplexml_load_string($data);
		} catch(GepardException $e){
			$this->api->restorestate("exceptiononerror");
			return false;
		}
		$this->api->restorestate("exceptiononerror");
		return $data;
	}
	
}
